package com.ruoyi.member.service.impl;


import com.ruoyi.common.utils.ThreadTask;
import com.ruoyi.integral.domain.CustomerPoint;
import com.ruoyi.integral.service.CustomerPointService;
import com.ruoyi.marketing.domain.Coupon;
import com.ruoyi.marketing.domain.RegisterMarketing;
import com.ruoyi.marketing.mapper.CouponMapper;
import com.ruoyi.marketing.service.CouponService;
import com.ruoyi.marketing.service.RegisterMarketingService;
import com.ruoyi.member.domain.UmsMember;
import com.ruoyi.member.mapper.UmsMemberMapper;
import com.ruoyi.member.service.IUmsMemberService;
import com.ruoyi.member.service.RegisterService;
import com.ruoyi.member.service.RegisterServiceApi;
import com.ruoyi.setting.domain.LsStationLetter;
import com.ruoyi.setting.service.ILsStationLetterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * 注册服务聚合接口实现
 */
@Service
public class RegisterServiceApiImpl implements RegisterServiceApi {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(RegisterServiceApiImpl.class);

    /**
     * 注入注册服务
     */
    @Autowired
    private RegisterService registerService;

    /**
     * 注入注册营销服务
     */
    @Autowired
    private RegisterMarketingService registerMarketingService;

    /**
     * 注入会员积分服务
     */
    @Autowired
    private CustomerPointService customerPointService;
    /**
     * 注入会员数据库接口
     */
    @Autowired
    private UmsMemberMapper customerMapper;

    /**
     * 注入优惠券服务
     */
    @Autowired
    private CouponService couponService;
    @Autowired
    private ILsStationLetterService letterService;
    /**
     * 密码工具类
     */
    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    /**
     * 注入会员服务
     */
    @Autowired
    private IUmsMemberService customerService;
    /**
     * 注入优惠券mapper
     */
    @Autowired
    private CouponMapper couponMapper;

    @Override
    @Transactional
    public int registerCustomer(long storeId, String mobile, String password, String code, String originCode, String recommondCode) {
        logger.debug("registerCustomer and mobile :{} \r\n code:{} \r\n: originCode{} \r\n recommondCode:{}", mobile, code, originCode, recommondCode);
        //注册用户
        int res = registerService.registerCustomer(storeId, mobile, password, code, originCode, recommondCode);
        //注册成功后执行注册营销
        if (res > 0) {
            ThreadTask.getInstance().addTask(() -> {
                registerCoupon(res);
            });
        }
        return res;
    }

    /**
     * 注册赠送优惠券和积分
     *
     * @param userId
     */
    @Override
    public void registerCoupon(long userId) {
        try {
            //查找注册营销
            RegisterMarketing registerMarketing = registerMarketingService.queryRegisterMarketing();
            if (!ObjectUtils.isEmpty(registerMarketing)) {
                if (registerMarketing.isEffective()) {
                    LsStationLetter letter = new LsStationLetter();
                    letter.setCustomerId(userId);
                    letter.setDelFlag(1);
                    letter.setTitle("注册送积分：" + registerMarketing.getPointNum());
                    letter.setContent("注册送积分：" + registerMarketing.getPointNum());
                    letter.setCreateTime(new Date());
                    letterService.insertLsStationLetter(letter);
                    //赠送积分
                    logger.info("registerCustomer success : present point");
                    customerPointService.addCustomerPoint(CustomerPoint.buildForRegister(userId, registerMarketing.getPointNum()));
                }
                if (registerMarketing.isCanReceiveCoupon()) {
                    //赠送优惠券
                    LsStationLetter letter = new LsStationLetter();
                    letter.setCustomerId(userId);
                    letter.setDelFlag(2);
                    boolean flag = true;
                    if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(registerMarketing.getCouponId())) {
                        logger.error("receiveCoupon fail:customerId or couponId is empty");
                        flag = false;
                    }
                    Coupon coupon = couponMapper.queryCouponByIdForReceive(registerMarketing.getCouponId(), 2);
                    if (ObjectUtils.isEmpty(coupon)) {
                        logger.error("receiveCoupon error : coupon is not exist");
                        flag = false;
                    }
                    if (coupon.getEndTime().isBefore(LocalDateTime.now())) {
                        logger.error("receiveCoupon error : activity finish");
                        flag = false;
                    }
                    if (flag) {
                        letter.setTitle("注册优惠券：" + coupon.getName());
                        letter.setCreateTime(new Date());
                        letter.setContent(coupon.getId() + "");

                        if (couponService.receiveCoupon(userId, registerMarketing.getCouponId(), 2) == 1) {
                            letterService.insertLsStationLetter(letter);
                            logger.info("registerCustomer success : present coupon");
                        } else {

                        }

                    }

                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }


    }

    @Override
    @Transactional
    public int bindMobile(long customerId, String mobile, String password, String code, String originCode, String recommondCode, long storeId) {
        logger.debug("bindMobile and mobile :{} \r\n code:{} \r\n: originCode{} \r\n recommondCode:{}", mobile, code, originCode, recommondCode);
        //注册用户
        logger.debug("bindMobile and mobile :{} \r\n code:{} \r\n: originCode{} \r\n recommondCode:{}", mobile, code, originCode, recommondCode);

        if (StringUtils.isEmpty(code)) {
            logger.error("bindMobile fail due to code is error...");
            return -1;
        }

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            logger.error("bindMobile fail due to mobile or password is empty...");
            return -2;
        }
        // 校验验证码是否正确
        if (!code.equals(originCode)) {
            logger.error("bindMobile fail due to code is error...");
            return -1;
        }
        UmsMember existCustomer = customerService.queryCustomerByName(mobile, storeId);
        // 判断手机号码是否存在
        if (existCustomer != null) {
            UmsMember customer = customerService.queryCustomerInfoById(customerId);
            existCustomer.setUpdateTime(new Date());
            existCustomer.setH5OpenId(customer.getH5OpenId());
            existCustomer.setAppletOpenId(customer.getAppletOpenId());
            existCustomer.setAppOpenId(customer.getAppOpenId());
            customerService.deleteUmsMemberById(customerId);
            return customerService.updateCustomer(existCustomer);
        }

        // 进行会员注册
        UmsMember customer = customerService.queryCustomerInfoById(customerId);
        // 设置会员密码
        customer.setPassword(passwordEncoder.encode(customer.getPassword()));
        customer.setConsumptionAmount(BigDecimal.ZERO);
        //设置自己的推荐码
        customer.addSelfRecommondCode();

        // 如果有推荐人 则查询推荐人信息
        if (customer.hasRecommonded()) {
            // 推荐人
            UmsMember recommonded = customerMapper.queryCustomerByRecommondCode(customer.getRecommondCode(), storeId);

            // 如果推荐人不存在  则返回错误
            if (Objects.isNull(recommonded)) {
                logger.error("addCustomer fail due to recommoned is not exist...and code:{}", customer.getRecommondCode());
                return -10;
            }
            // 设置推荐人的会员id
            customer.setRecommended(recommonded.getId());
            customer.setInterest(recommonded.getNickname());
            // 设置会员的二级推荐人/ 推荐人的推荐人
            customer.setSRecommended(recommonded.getRecommended());
        }

        return 0;
    }
}
